import util from "@/common/tools/utils.js";

var ims = {}

ims.SPLITSTR = '##@@@##';

 
ims.house_to_msg =  function(house)  {
	return  {
	  id: house.id,
	  thumb: house.thumb,
	  title: house.title,
	  area: house.area,
	  infotype: house.infotype,
	  loyer: house.loyer,
	  prix_unitaire: house.prix_unitaire,
	  linkurl: "/pages/show/show?id="+ house.id
	} 
}
ims.onSendHouse =  function(myopenid, toopenid, house, baseparam){
 
	if( typeof house !=='object' ){
		console.log('没有房源信息', house);
		return false;
	}
	var keyexit = uni.getStorageSync(  'hid-' + house.id );
    if( keyexit){
		console.log('已经发送过此房源');
		return false;
	}
    uni.setStorage({
      //设置缓存过期时间为1天
      data: {data: 1, expire: Date.parse(new Date()) + 24*1*3600*1000},
      key:  'hid-' + house.id,
    });
 
    const msginfo = ims.message_type_house(
		  myopenid, 
		  toopenid, 
		  house.title, 
		  house.area +' '+house.infotype+' '+ house.loyer+' '+house.prix_unitaire + ims.SPLITSTR + house.thumb,
		  house.linkurl 
	  );
	 
    //把房源消息发送出去到服务器保存；
    return ims.send_message(  Object.assign(msginfo, baseparam) ) 
  } 
 
  ims.history_message = function( params){
 
	 return	util.sendPost(
			util.getModuleUrl('tallk','ajaxMsgList' )
			,params
	 ) 
    
  }
  /**消息格式 TIMTextElem*/
  ims.message_type_text = function(myopenid, toopenid,message){
      return {
        sendto :  toopenid,
        froomAccount : myopenid,
        msgType : 'TIMTextElem',
        time : Math.round(new Date().getTime()/1000) ,
        msgcontent : message,
      }
  }
  //图片格式
  ims.message_type_image = function(myopenid, toopenid,imgurl){
    return {
      sendto :  toopenid,
      froomAccount : myopenid,
      msgType : 'TIMImageElem',
      time : Math.round(new Date().getTime()/1000) ,
      msgcontent : '图片消息',
      data: '',
      url: imgurl
    }
} 
  /**发送房源消息 TIMCustomElem*/
  ims.message_type_house = function(myopenid, toopenid,
    housetitle, extinfo, links){
      return {
        sendto :  toopenid,
        froomAccount : myopenid,
        msgType : 'TIMCustomElem',
        time : Math.round(new Date().getTime()/1000) ,
        msgcontent : housetitle,
        data :   extinfo,
        url :links
      }
    }

    /**统一的msginfo 前端显示消息格式 */
    ims.message_formact = function(messages){
        
        if(messages.constructor !== Array){
            messages = [messages]
        }
        let rets = [];
        for(let i=0; i< messages.length; i++){
         
          let data = messages[i];
          //console.log(data)
          let content= data.content;
          let msgData = data.Data;
          let msgface = '/kbwdl_shequzufang/static/images/house_face.jpg';
          if(data.msgType == 'TIMCustomElem'){
            if(msgData.indexOf(ims.SPLITSTR)>0){
              let tmp = msgData.split(ims.SPLITSTR)
              msgData = tmp[0];
              msgface = tmp[1];
            }
            
          }
 
          
          // 把消息添加到聊天记录列表
          rets.push( {
            id: data.id,
            addtime:  data.addtime,
            content:  content,
            Data: msgData,
            msgface: msgface,
            Ext : data.Ext,
            msgType : data.msgType,
            thumb: data.thumb,
            To_Account: data.To_Account,
            whocss: data.whocss //自己的aui-chat-right
          });
        }
      return rets;
    }
  /**发送一条消息 */

  ims.send_message = function( msginfo){
     console.log('发送消息', msginfo)
	 return	util.sendPost(
			util.getModuleUrl('tallk','saveMsg'), 
			msginfo
	 ) 
  }
  /**获取发给我的最新一条消息 */
  ims.send_me_last_msg = function(  params){
    
    return	util.sendPost(
    	 util.getModuleUrl('tallk','LastMsg')
		 , {  page:0  , ...params}
    ) 
 
  }
/**
 * 选择图片进行上传
 */
  ims.uploadFile = function(cback){
    const that = this
 
    wx.chooseImage({
      count: 9,
      success: function (res) {
      
        let transfile = {};
        transfile.path = res.tempFilePaths;
        that.uploadimg(transfile,cback);
      },
    });
  }
  /**这个是分开上传多张图片 
   * transfile 返回的数据格式
 * res.data 的格式
  * "kbwdl_shequzufang/201804/3275257180143965.jpg#https://api.guifun.com/attachment/kbwdl_shequzufang/201804/3275257180143965.jpg"
  */

  //多张图片上传
  ims.uploadimg = function (data, cback) {
    var self = this,
      i = data.i ? data.i : 0,//当前上传的哪张图片
      success = data.success ? data.success : 0,//上传成功的个数
      fail = data.fail ? data.fail : 0;//上传失败的个数
    var app = getApp();
    /**调用接口上传 */
    let uploadUrl = app.util.url('entry/wxapp/transfile', { m: 'kbwdl_shequzufang' });
    wx.showLoading({
      title: '上传图片',
    })
   const uploadTask = wx.uploadFile({
      url: uploadUrl,
      filePath: data.path[i],
      name: 'upfile',
      formData: {},
      success: function (resp) {
        success++;     
        let url = resp.data;
        
        let path = url.split('#');
        cback(path[1])
        //这里可能有BUG，失败也会执行这里,所以这里应该是后台返回过来的状态码为成功时，这里的success才+1
      },
      fail: function (res) {
        fail++;//图片上传失败，图片上传失败的变量+1
        //console.log('fail:' + i + "fail:" + fail);
      },
      complete: function () {

        i++;//这个图片执行完上传后，开始上传下一张
        if (i == data.path.length) {   //当图片传完时，停止调用          
          wx.hideLoading({
            success: (res) => {},
          })      
         // console.log('成功：' + success + " 失败：" + fail);
        } else {//若图片还没有传完，则继续调用函数           
          data.i = i;
          data.success = success;
          data.fail = fail;
          self.uploadimg(data, cback);
        }

      }
    });
    /** */
    uploadTask.onProgressUpdate((res) => {
      if (res.progress < 100) {
       // self.setData({ show_progress: 1, progress_per: res.progress })
      } else {
       // self.setData({ show_progress: 0 })
      }
 
    })
  }

export  {ims} ;